package crm8000.services

import crm8000.Models.Invertory;
import crm8000.Models.InvertoryDetail;
import crm8000.Models.Warehouse;
import grails.transaction.Transactional

@Transactional
class InvertoryService {

	def warehouseList() {
		return Warehouse.createCriteria().list {
			eq "inited", true
			order "code"
		}
	}

	def invertoryList(String warehouseId) {
		return Invertory.createCriteria().list {
			warehouse { eq "id", warehouseId}
			goods { order "code" }
		}
	}

	def invertoryDetailList(params) {
		Date dtFrom, dtTo

		if (!params.dtFrom) {
			dtFrom = Date.parse("yyyy-MM-dd", (new Date() - 7).format("yyyy-MM-dd"))
		} else {
			dtFrom = Date.parse("yyyy-MM-dd",params.dtFrom)
		}

		if (!params.dtTo) {
			dtTo = Date.parse("yyyy-MM-dd", new Date().format("yyyy-MM-dd"))
		} else {
			dtTo = Date.parse("yyyy-MM-dd", params.dtTo)
		}

		return InvertoryDetail.createCriteria().list(max: params.limit, offset: params.start) {
			warehouse { eq "id", params.warehouseId }
			goods { eq "id", params.goodsId }
			between "bizDate", dtFrom, dtTo
			order "bizDate"
		}
	}

	def invertoryDetailListTotalCount(params) {
		Date dtFrom, dtTo

		if (!params.dtFrom) {
			dtFrom = Date.parse("yyyy-MM-dd", (new Date() - 7).format("yyyy-MM-dd"))
		} else {
			dtFrom = Date.parse("yyyy-MM-dd",params.dtFrom)
		}

		if (!params.dtTo) {
			dtTo = Date.parse("yyyy-MM-dd", new Date().format("yyyy-MM-dd"))
		} else {
			dtTo = Date.parse("yyyy-MM-dd", params.dtTo)
		}

		return InvertoryDetail.createCriteria().get {
			projections { count("id")}
			warehouse { eq "id", params.warehouseId }
			goods { eq "id", params.goodsId }
			between "bizDate", dtFrom, dtTo
			order "bizDate"
		}
	}
}
